<template>
	<view>
		<view>
			<view>
				<view class="logo">
					<image class="logo-image margin-top-xl" style="width: 200rpx; height: 200rpx;" src="/static/qlzc.png"></image>
					<view class="text-xl text-darkgrey">欢迎登录</view>
				</view>
			</view>
			<view class="main margin-top-xl">
				<wInput
					v-model="loginForm.username"
					type="text"
					maxlength="20"
					:placeholder="isPhoneLogin ? '请输入手机号码' : '请输入账号'"
				></wInput>
				<wInput
						v-model="loginForm.code"
						v-show="isPhoneLogin"
						:isShowCode="true"
						type="text"
						maxlength="20"
						ref="smsCodeRef"
						@setCode="showGraphCodeModal"
						placeholder="请输入短信验证码"
				></wInput>
				<wInput
					v-show="!isPhoneLogin"
					v-model="loginForm.password"
					type="password"
					maxlength="20"
					placeholder="请输入密码"
				></wInput>
				<wInput
						v-model="loginForm.code"
						v-show="!isPhoneLogin"
						:isShowRandom="true"
						:codeImgSrc="code.src"
						type="text"
						:maxlength="code.len"
						@refreshCode="refreshCode"
						placeholder="请输入验证码"
				></wInput>
			</view>

			<view class="flex justify-between" style="padding-left: 5%;padding-right: 5%;">
				<view>
					<!-- #ifdef MP-WEIXIN-->
					<view class="text-blue text-sm " @click="showModal='show'">微信登录</view>
					<!-- #endif -->
				</view>
				<view>
					<view class="text-blue text-sm " @click="changeLoginType">{{isPhoneLogin?'账号密码登录':'手机验证码登录'}}</view>
				</view>
			</view>
			<view style="margin-top: 30px">
				<button class="cu-btn bg-gradual-purple round margin-tb-sm lg login" @click="startLogin">
					登 录
				</button>
			</view>
		</view>
		<!-- 用户隐私政策授权弹框 -->
		<privacy-policy-popup v-if="showPrivacyPolicy"></privacy-policy-popup>
		<!-- 授权弹框 -->
		<view class="cu-modal bottom-modal" :class="showModal?'show':''">
			<view class="cu-dialog">
				<view class="cu-bar bg-white">
					<view class="action text-gray" @tap="showModal=''">取消</view>
				</view>
				<view class="padding-xl text-lg">{{modalContent}}</view>
				<button class="cu-btn bg-orange margin-tb-sm lg margin-top-sm " style="margin-right: 10%;margin-left: 10%;width: 80%;height: 40px;margin-bottom: 20px;"
				open-type="getUserInfo" @getuserinfo="wxLogin()">确认</button>
			</view>
		</view>
		<view class="margin-top flex justify-center text-sm" v-show="showPrivacyPolicy">
			<text>登录即代表您同意</text><navigator class="text-blue text-sm" :url="'/pages/public/webview/webview?title=用户协议&url='+protocolUrl">{{' 用户协议 '}}</navigator>和<navigator class="text-blue text-sm  " :url="'/pages/public/webview/webview?title=隐私政策&url='+privacyPolicyUrl">{{' 隐私政策'}}</navigator>
		</view>
		<!-- 发送短信之前的图形验证码 -->
		<graph-code ref="graphCodeRef" :phone="loginForm.username" @onSend="sendSms"></graph-code>
	</view>
</template>

<script>

	var _this;
	const app = getApp();
	import __config from "@/config/env";
	import wInput from '@/components/watch-login/watch-input.vue' //input
	import wButton from '@/components/watch-login/watch-button.vue' //button
	import privacyPolicyPopup from '@/components/basic-components/privacy-policy/privacy-policy-popup.vue';
	import GraphCode from '@/components/graph-code/graph-code.vue'; // 图形验证码

	import api from '@/api/api';
	import { randomLenNum, encryption } from '@/utils/util';
	import service from '@/store/service.js';

	export default {
		data() {
			return {
				showPrivacyPolicy: __config.showPrivacyPolicy,
				privacyPolicyUrl: __config.privacyPolicyUrl,
				protocolUrl: __config.protocolUrl,
				code: {
					src: "/code",
					value: "",
					len: 4,
					type: "image"
				},
				loginForm:{
					username: '17628500916',
					phone: '',
					code: '',
					password: '17628500916',
					randomStr: '',
				},
				openId: '',
				isPhoneLogin: false,
				showModalLogin: false,//弹框
				showModal: false,//弹框
				showPrivacyPolicies: false,//弹框
				modalContent: '需要您的授权才能使用微信登录！',//
			};
		},
		components:{
			wInput,
			wButton,
			privacyPolicyPopup,
			GraphCode,
		},
		mounted() {
			_this= this;
			//进入登录页面表示已经退出，需要退出IM
			if(this.$store&&this.$im)
			this.$store.dispatch("IMuser/logOutIM", this.$im)
			//this.isLogin();
		},
		created() {
			this.refreshCode();
		},
		methods: {
			// 显示图形验证码弹框
			showGraphCodeModal() {
				if (this.loginForm.username == "") {
					 uni.showToast({
						icon: 'none',
						position: 'bottom',
						title: '请输入手机号码'
					});
					return;
				}
				//验证手机号码
				if(!(/^1(3|4|5|6|7|8|9)\d{9}$/.test(this.loginForm.username))){
					uni.showToast({title: '请填写正确的手机号码', icon:"none"});
					return;
				}
				this.$refs.graphCodeRef.showModal()
			},
			wxLogin(){
				var that = this;
				this.showModal = '';
				uni.login({
					provider: "weixin",
					success: (res) => {
						//是否获取openId
						// let wxLoginUrl = api.account + "/users/wxCodeLogin/" + res.code;
						// httpRequest.httpGetLogin(wxLoginUrl, function(res){
						// 	that.openId = res.openId;
						// 	if(res.flag){ // 判断是否有该用户信息
						// 		that.accessTokenLogin(res.tokenData.access_token);
						// 	} else {
						// 		that.showModalLogin = true;
						// 	}
						// });
					},
					fail: (e) => {
						console.log("fail", e);
					}
				});
			},
			getPhoneNumber (e) {

			},
		    startLogin(){
				//登录
				if(this.isRotate){
					//判断是否加载中，避免重复点击请求
					return false;
				}
				if (this.loginForm.username.length == "") {
				     uni.showToast({
				        icon: 'none',
						position: 'bottom',
				        title: this.isPhoneLogin ? '请输入手机号码':'请输入登录账号'
				    });
				    return;

				}
		        if (this.isPhoneLogin) {
					if(this.loginForm.code.length == ""){
						uni.showToast({
							icon: 'none',
							position: 'bottom',
							title: '请输入短信验证码'
						});
						return;
					}
		        }else {
		        	if(this.loginForm.password.length == ""){
						uni.showToast({
							icon: 'none',
							position: 'bottom',
							title: '请输入密码信息'
						});
						return;
					}
					if(this.loginForm.code.length == ""){
						uni.showToast({
							icon: 'none',
							position: 'bottom',
							title: '请输入验证码'
						});
						return;
					}
				}

				if(this.isPhoneLogin){ // 手机验证码登录
					api.login.loginByPhone(this.loginForm.username, this.loginForm.code).then(response=>{
						if(response){
							service.saveAccessToken(response);
							this.getUserInfo();
						}
					}).catch(response => {
						uni.showToast({
							icon: 'none',
							position: 'bottom',
							title: '登录失败'
						});
						this.refreshCode();
					});
				} else { // 账号密码登录
					const loginInfo = encryption({
						data: this.loginForm,
						key: __config.securityKey,
						param: ['password']
					});
					api.login.loginByUsername(loginInfo).then(response=>{
						// 登录成功 保存登录数据、本次登录的token
						service.saveAccessToken(response);
						// 获取个人信息
						this.getUserInfo();
					}).catch(response => {
						uni.showToast({
							icon: 'none',
							position: 'bottom',
							title: response.msg
						});
						this.refreshCode();
					});

				}
		    },
			refreshCode(){
				this.loginForm.code = ''
				this.loginForm.randomStr = randomLenNum(this.code.len, true)
				this.code.type === 'text'
						? (this.code.value = randomLenNum(this.code.len))
						: (this.code.src = api.login.randomStr + this.loginForm.randomStr)
			},
			sendSms(graphCode){
				if (this.loginForm.username == "") {
				     uni.showToast({
				        icon: 'none',
						position: 'bottom',
				        title: '请输入手机号码'
				    });
				    return;
				}
				//验证手机号码
				if(!(/^1(3|4|5|6|7|8|9)\d{9}$/.test(this.loginForm.username))){
					uni.showToast({title: '请填写正确的手机号码', icon:"none"});
					return;
				}
				if (!graphCode) {
					uni.showToast({
						title: '请输入图形验证码',
						icon: 'none',
						duration: 3000
					});
					return;
				}
				// 发送验证码
				this.handleSend(graphCode);
			},
			handleSend(graphCode) { //发送验证码
				api.login.sendCode({
					phone: this.loginForm.username,
					type: 1,
					graphCode
				}).then(response => {
					if (response.code == '0') {
						uni.showToast({title: '验证码发送成功'});
						// 启动倒计时
						this.$refs.smsCodeRef.runCode(60);
						this.$refs.graphCodeRef.hideModal()
					} else {
						this.$refs.graphCodeRef.refreshGraphCode()
						uni.showToast({title: response.msg,icon:"none"});
					}
				}).catch((response) => {
						this.$refs.graphCodeRef.refreshGraphCode()
						uni.showToast({title: response.msg,icon:"none"});
				})
			},
			accessTokenLogin(access_token){

			},
			getUserInfo(){
				api.getUserInfo().then(async response=>{
					// 保存用户信息
					service.saveUserInfo(response.data.sysUser);
					// 保存用户权限
					service.saveUserPermissions(response.data.permissions);
					//初始化IMIM
					app.initJIM()
					app.getuiAliasBind()
					uni.reLaunch({
						url: '/pages/home/index'
					});

				}).catch(response => {
					uni.showToast({
						icon: 'none',
						position: 'bottom',
						title: response.msg
					});
				});
			},
			changeLoginType(){
				this.loginForm.code = '';
				this.isPhoneLogin = !this.isPhoneLogin;
			},
		}
	}
</script>

<style>
	.logo{
		margin-top: 80rpx;
		margin-left: 50rpx;
	}

	.logo-image{
		width: 260upx;
		height: 120upx;
	}

	.login{
		 margin-right: 10%;
		 margin-left: 10%;
		 width: 80%;
		 height: 45px;
		 box-shadow:0px 10px 20px #c5c7ec;
	}
</style>
